//
//  ScVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/22.
//

import UIKit

class ScVC: BaseVC {
    
    var collectionView: UICollectionView!
    
    var dataArray: [[String: Any]] = []
    var pageNum: Int = 1
    var pageSize: Int = 10
    var keyWord: String = ""
    var status: String = ""
    
    var sx_state: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadData))
        collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        loadData()
    }
    
    // 数据刷新
    @objc func loadData() {
        pageNum = 1
        dataArray.removeAll()
        loadMoreData()
    }
    @objc func loadMoreData() {
        let paramet: [String: String] = [
            "keyWord" : keyWord,
            "status": status,
            "assessStatus": "",
            "pageNo" : pageNum.description,
            "pageSize" : pageSize.description
        ]
        EWERequest.lgf("screening", paramet, .get) { [weak self] (data) in
            let result = (data["result"] as? [[String: Any]]) ?? []
            if result.count > 0 {
                self?.dataArray += result
                self?.pageNum += 1
            }
            self?.collectionView.reloadData()
            self?.endRefreshing()
            if result.count == 0 {
                self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    func endRefreshing() {
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
    }
    
    @objc func s_sx(_ sender: UITapGestureRecognizer) {
        SxV().showIn(self.view, ["筛查状态"], ["筛查状态": ["正在筛查", "筛查完成", "筛查失败"]], [self.sx_state]) { [weak self] (sxv, name, state) in
            if state.first == 0 {
                self?.status = ""
            } else if state.first == 1 {
                self?.status = "10"
            } else if state.first == 2 {
                self?.status = "20"
            } else if state.first == 3 {
                self?.status = "30"
            }
            if self?.sx_state != state.first {
                self?.loadData()
            }
            self?.sx_state = state.first ?? 0
        }
    }
    
}

extension ScVC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        keyWord = textField.text ?? ""
        loadData()
    }
}

extension ScVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 170)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: ScCell.self, for: indexPath)
        cell.delegate = self
        cell.tzzx.text = (dataArray[indexPath.item]["no"] as? String) ?? ""
        cell.cjsj.text = "创建时间：" + (((dataArray[indexPath.item]["createdTime"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_TimeStr("yyyy-MM-dd HH:mm:ss"))
        cell.xm.text = "姓名：" + (((dataArray[indexPath.item]["patient"] as? [String: Any])?["name"] as? String) ?? "")
        cell.nl.text = "年龄：" + ((((dataArray[indexPath.item]["patient"] as? [String: Any])?["birthday"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_AgeWithDateOfBirth().description + "岁")
        cell.tw.text = "体位：" + ((dataArray[indexPath.item]["position"] as? String) ?? "")
        cell.phcd.text = "配合程度：" + ((dataArray[indexPath.item]["coordinate"] as? String) ?? "")
        let aiStatus = (dataArray[indexPath.item]["aiStatus"] as? Int) ?? 10
        reloadStatus(cell, aiStatus, indexPath.item)
        return cell
    }
    
    func reloadStatus(_ cell: ScCell, _ aiStatus: Int, _ index: Int) {
        let status = (dataArray[index]["status"] as? Int) ?? 10
        if status == 10 {
            cell.zt.text = "正在筛查"
            cell.zt.textColor = UIColor.init(lgf_HexString: "8D969D")
        } else if status == 20 {
            cell.zt.text = "筛查完成"
            cell.zt.textColor = UIColor.init(lgf_HexString: "0F88F2")
        } else if status == 30 {
            cell.zt.text = "待确定"
            cell.zt.textColor = UIColor.init(lgf_HexString: "F27C0F")
        }
        if aiStatus == 10 {
            cell.fx.text = "分析中"
            cell.fx.isUserInteractionEnabled = false
            cell.fx.textColor = UIColor.init(lgf_HexString: "F27C0F")
            cell.fx_i.image = #imageLiteral(resourceName: "jiazai--kuai")
            cell.fx_s.isHidden = true
        } else if aiStatus == 20 {
            cell.fx.text = "AI分析"
            cell.fx.isUserInteractionEnabled = true
            cell.fx.textColor = UIColor.init(lgf_HexString: "0F88F2")
            cell.fx_i.image = #imageLiteral(resourceName: "bangdin备份")
            cell.fx_s.isHidden = false
            cell.fx_s.text = "完成分析"
            cell.fx_s.backgroundColor = UIColor.init(lgf_HexString: "0F88F2")?.withAlphaComponent(0.05)
            cell.fx_s.textColor = UIColor.init(lgf_HexString: "0F88F2")
            cell.fx_s.layer.borderColor = UIColor.init(lgf_HexString: "0F88F2")?.withAlphaComponent(0.1).cgColor
        } else if aiStatus == 30 {
            cell.fx.text = "AI分析"
            cell.fx.isUserInteractionEnabled = true
            cell.fx.textColor = UIColor.init(lgf_HexString: "0F88F2")
            cell.fx_i.image = #imageLiteral(resourceName: "bangdin备份")
            cell.fx_s.isHidden = false
            cell.fx_s.text = "无法解析"
            cell.fx_s.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")?.withAlphaComponent(0.05)
            cell.fx_s.textColor = UIColor.init(lgf_HexString: "F27C0F")
            cell.fx_s.layer.borderColor = UIColor.init(lgf_HexString: "F27C0F")?.withAlphaComponent(0.1).cgColor
        }
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = ScxqVC()
        vc.id = (dataArray[indexPath.item]["id"] as? String) ?? ""
        self.navigationController?.show(vc, sender: self)
    }
}

extension ScVC: ScCellDelegate {
    func selectFX(_ cell: ScCell, _ index: Int) {
        let id = (dataArray[index]["id"] as? String) ?? ""
        let paramet: [String: Any] = [
            "aiStatus": 10
        ]
        EWERequest.lgf("screening/" + id, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            self?.reloadStatus(cell, 10, index)
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
}
